package com.onec.service.netty.channelpipeline;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

public class OutPipeLine {

  static class SimpleHandleA extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
        throws Exception {
      System.out.println("A : 被调用");
      super.write(ctx, msg, promise);
    }
  }

  static class SimpleHandleB extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
        throws Exception {
      System.out.println("B: 被调用");
      super.write(ctx, msg, promise);
    }
  }


  @Test
  public void testPipeline() {
    ChannelInitializer i = new ChannelInitializer<EmbeddedChannel>() {
      @Override
      protected void initChannel(EmbeddedChannel ch) throws Exception {
        ch.pipeline().addLast(new SimpleHandleA());
        ch.pipeline().addLast(new SimpleHandleB());

      }
    };

    EmbeddedChannel embeddedChannel = new EmbeddedChannel(i);

    ByteBuf byteBuf = Unpooled.buffer();
    byteBuf.writeInt(2);

    embeddedChannel.writeOutbound(byteBuf);
    embeddedChannel.flush();
    embeddedChannel.close();
  }

}


